$(function () {
  const form = layui.form;
  const layer = layui.layer;

  getArticlecate();
  function getArticlecate() {
    $.ajax({
      method: "get",
      url: "/my/article/cates",
      success: function (res) {
        console.log(res);
        const Str = res.data
          .map(function (item) {
            return `
      <tr>
      <td>${item.name}</td>
      <td>${item.alias}</td>
      <td>
      <button type="button" class="layui-btn layui-btn-xs" data-id="${item.Id}" id="changefn">编辑</button>
      <button type="button" class="layui-btn layui-btn-danger layui-btn-xs"  data-id="${item.Id}" id="deleteCate">删除</button>
      </td>
    </tr>
      `;
          })
          .join("");
        $("tbody").html(Str);
      },
    });
  }

  // 为添加类别按钮绑定点击事件
  let indexAdd = null;
  $("#btnadd").on("click", function () {
    indexAdd = layer.open({
      type: 1,
      area: ["500px", "250px"],
      title: "添加文章分类",
      content: $("#dialog-add").html(),
    });
  });
  // 添加功能
  $("body").on("submit", "#form-add", function (e) {
    e.preventDefault();
    $.ajax({
      method: "post",
      url: "/my/article/addcates",
      data: $(this).serialize(),
      success: function (res) {
        console.log(res);
        if (res.status !== 0) {
          return layer.msg(res.message);
        }
        layer.msg(res.message);
        getArticlecate();
        layer.close(indexAdd);
      },
    });
  });
  //删除功能
  $("tbody").on("click", "#deleteCate", function (e) {
    e.preventDefault();
    let id = $(this).attr("data-id");
    $.ajax({
      method: "get",
      url: `/my/article/deletecate/${id}`,
      success: function (res) {
        console.log(res);
        if (res.status !== 0) {
          return layer.msg(res.message);
        }
        layer.msg(res.message);
        getArticlecate();
      },
    });
  });

  // 编辑功能
  let changeeFN = null;
  $("tbody").on("click", "#changefn", function () {
    changeeFN = layer.open({
      type: 1,
      area: ["500px", "250px"],
      title: "添加文章分类",
      content: $("#dialog-edit").html(),
    });

    let id = $(this).attr("data-id");
    $.ajax({
      method: "get",
      url: `/my/article/cates/${id}`,
      success: function (res) {
        console.log(res);
        if (res.status !== 0) {
          return layer.msg(res.message);
        }
        form.val("form-edit", res.data);
      },
    });
  });

  $("body").on("submit", "#form-edit", function (e) {
    e.preventDefault();
    $.ajax({
      method: "post",
      url: "/my/article/updatecate",
      data: $(this).serialize(),
      success: function (res) {
        console.log(res);
        if (res.status !== 0) {
          return layer.msg(res.message);
        }
        layer.msg(res.message);
        getArticlecate()
        layer.close(changeeFN)
      },
    });
  });
});
